/*-
 *   BSD LICENSE
 *
 *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
 *   All rights reserved.
 *
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions
 *   are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *     * Neither the name of Intel Corporation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Sample application demostrating how to do packet I/O in a multi-process
 * environment. The same code can be run as a primary process and as a
 * secondary process, just with a different proc-id parameter in each case
 * (apart from the EAL flag to indicate a secondary process).
 *
 * Each process will read from the same ports, given by the port-mask
 * parameter, which should be the same in each case, just using a different
 * queue per port as determined by the proc-id parameter.
 */

#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <sys/queue.h>
#include <getopt.h>
#include <signal.h>
#include <inttypes.h>

#include <rte_common.h>
#include <rte_log.h>
#include <rte_memory.h>
#include <rte_memzone.h>
#include <rte_launch.h>
#include <rte_eal.h>
#include <rte_per_lcore.h>
#include <rte_lcore.h>
#include <rte_debug.h>
#include <rte_atomic.h>
#include <rte_branch_prediction.h>
#include <rte_ring.h>
#include <rte_debug.h>
#include <rte_interrupts.h>
#include <rte_pci.h>
#include <rte_ether.h>
#include <rte_ethdev.h>
#include <rte_mempool.h>
#include <rte_memcpy.h>
#include <rte_mbuf.h>
#include <rte_string_fns.h>
#include <rte_cycles.h>

#define RTE_LOGTYPE_APP RTE_LOGTYPE_USER1

#define NB_MBUFS 64*1024 /* use 64k mbufs */
#define MBUF_CACHE_SIZE 256
#define PKT_BURST 32
#define RX_RING_SIZE 512
#define TX_RING_SIZE 128


#define MAX_ARGV_LEN 32
#define MAX_ARGV_COUNT 16
//static char* g_nic = NULL;
static int g_port = 0;
static int g_cpu = 0x01;
static int g_num = 1;

/* structure to record the rx and tx packets. Put two per cache line as ports
 * used in pairs */
struct port_stats{
	unsigned rx;
	unsigned tx;
	unsigned drop;
} __attribute__((aligned(RTE_CACHE_LINE_SIZE / 2)));

static struct port_stats pstats;

/* prints the usage statement and quits with an error message */
static void
smp_usage(const char *prgname, const char *errmsg)
{
	printf("\nError: %s\n",errmsg);
	printf("\n%s [EAL options] -- -p <port> "
			"-p         : what ports are to be used\n"
			"--num-procs: the number of processes which will be used\n"
			"\n",
			prgname);
	exit(1);
}


/* signal handler configured for SIGTERM and SIGINT to print stats on exit */
static void
print_stats(int signum)
{
	printf("\nExiting on signal %d\n\n", signum);
	printf("Port %u: RX - %u, TX - %u, Drop - %u\n", (unsigned)g_port,
			pstats.rx, pstats.tx, pstats.drop);
	exit(0);
}

/* Parse the argument given in the command line of the application */
static int
smp_parse_args(int argc, char **argv)
{
	int opt;
	char *prgname = argv[0];

	while ((opt = getopt(argc, argv, "c:p:")) != EOF) {
		switch (opt) {
		case 'p':
			g_port = strtol(optarg, NULL, 10);
			break;
		case 'c':
			g_cpu = strtoull(optarg, NULL, 16);
			break;
		default:
			smp_usage(prgname, "Cannot parse all command-line arguments\n");
		}
	}

	return 0;
}

/*
 * Initialises a given port using global settings and with the rx buffers
 * coming from the mbuf_pool passed as parameter
 */
static inline int
smp_port_init(uint8_t port, struct rte_mempool *mbuf_pool, uint16_t num_queues)
{
	struct rte_eth_conf port_conf = {
			.rxmode = {
				//.mq_mode	= ETH_MQ_RX_RSS,
				.split_hdr_size = 0,
				.header_split   = 0, /**< Header Split disabled */
				.hw_ip_checksum = 0, /**< IP checksum offload enabled */
				.hw_vlan_filter = 0, /**< VLAN filtering disabled */
				.jumbo_frame    = 0, /**< Jumbo Frame Support disabled */
				.hw_strip_crc   = 0, /**< CRC stripped by hardware */
				.max_rx_pkt_len = ETHER_MAX_LEN,
			},
			//.rx_adv_conf = {
			//	.rss_conf = {
			//		.rss_key = NULL,
			//		.rss_hf = ETH_RSS_IP,
			//	},
			//},
			.txmode = {
				.mq_mode = ETH_MQ_TX_NONE,
			}
	};
	const uint16_t rx_rings = num_queues, tx_rings = num_queues;
	struct rte_eth_dev_info info;
	int retval;
	uint16_t q;

	if (rte_eal_process_type() == RTE_PROC_SECONDARY)
		return 0;

	if (port >= rte_eth_dev_count())
		return -1;

	printf("# Initialising port %u ...\n", (unsigned)port);

	rte_eth_dev_info_get(port, &info);
	//info.default_rxconf.rx_drop_en = 1;

	retval = rte_eth_dev_configure(port, rx_rings, tx_rings, &port_conf);
	if (retval < 0)
		return retval;

	for (q = 0; q < rx_rings; q ++) {
		retval = rte_eth_rx_queue_setup(port, q, RX_RING_SIZE,
				rte_eth_dev_socket_id(port),
				&info.default_rxconf,
				mbuf_pool);
		if (retval < 0)
			return retval;
	}

	for (q = 0; q < tx_rings; q ++) {
		retval = rte_eth_tx_queue_setup(port, q, TX_RING_SIZE,
				rte_eth_dev_socket_id(port),
				NULL);
		if (retval < 0)
			return retval;
	}

	rte_eth_promiscuous_enable(port);

	retval  = rte_eth_dev_start(port);
	if (retval < 0)
		return retval;

	return 0;
}

static void display(const unsigned char* buf, int len)
{
	int i;
	for ( i = 0; i < len; i++ )
	{
		printf("%02x ", buf[i]);
		if( (i+1) % 16 == 0)
		{
			printf("\n");
			continue;
		}

		if( (i+1) % 8 == 0)
			printf(" ");
	}
	printf("\n");
}

/* Main function used by the processing threads.
 * Prints out some configuration details for the thread and then begins
 * performing packet RX and TX.
 */
static int
lcore_main(void *arg __rte_unused)
{
	const unsigned id = rte_lcore_id();
	const uint16_t q_id = 0; //(uint16_t)proc_id;
	unsigned i;
	uint8_t* pkt;
	int port = g_port;

	printf("lcore %u using queue %u of port %u\n", id, (unsigned)q_id, port);

	/* handle packet I/O from the ports, reading and writing to the
	 * queue number corresponding to our process number (not lcore id)
	 */

	display(NULL, 0);

	for (;;) {
		struct rte_mbuf *buf[PKT_BURST];

		const uint16_t rx_c = rte_eth_rx_burst(port, q_id, buf, PKT_BURST);
		if (rx_c == 0)
			continue;

		for (i = 0; i < rx_c; i++)
		{
			pkt = rte_pktmbuf_mtod(buf[i], void *);
			printf("=[%d]= %4d bytes =====\n", ++pstats.rx, buf[i]->pkt_len);
			//display(pkt, rte_pktmbuf_pkt_len(buf[i]));
			rte_pktmbuf_free(buf[i]);
		}

	}
}
/* Check the link status of all ports in up to 9s, and print them finally */
static void
check_port_link_status(uint8_t portid)
{
#define CHECK_INTERVAL 100 /* 100ms */
#define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
	uint8_t count;
	struct rte_eth_link link;

	printf("\nChecking link status");
	fflush(stdout);
	for (count = 0; count <= MAX_CHECK_TIME; count++) {
		memset(&link, 0, sizeof(link));
		rte_eth_link_get_nowait(portid, &link);
		if (link.link_status)
		{
			printf("Port %d Link Up - speed %u "
					"Mbps - %s\n", (uint8_t)portid,
					(unsigned)link.link_speed,
				(link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
					("full-duplex") : ("half-duplex\n"));
			return;
		}
		else
		{
			printf(".");
			fflush(stdout);
			rte_delay_ms(CHECK_INTERVAL);
		}
	}

	printf("Port %d Link Down\n", (uint8_t)portid);
}

/* Main function.
 * Performs initialisation and then calls the lcore_main on each core
 * to do the packet-processing work.

-c coremask
-p port
 */

int
main(int argc, char **argv)
{
	int ret;
	int rte_argc = 0;
	char rte_argvv[MAX_ARGV_COUNT][MAX_ARGV_LEN];
	char *rte_argv[MAX_ARGV_COUNT];

	static const char *_SMP_MBUF_POOL = "SMP_MBUF_POOL";
	
	enum rte_proc_type_t proc_type;
	struct rte_mempool *mp;

	signal(SIGTERM, print_stats);
	
	int num_queues = 1;
	int nb_ports, portid;

	smp_parse_args(argc, argv);


	snprintf(rte_argvv[rte_argc], MAX_ARGV_LEN, "client");
	rte_argv[rte_argc] = rte_argvv[rte_argc];
	rte_argc++;
	snprintf(rte_argvv[rte_argc], MAX_ARGV_LEN, "-c%d", g_cpu);
	rte_argv[rte_argc] = rte_argvv[rte_argc];
	rte_argc++;
	snprintf(rte_argvv[rte_argc], MAX_ARGV_LEN, "-n%d",  g_num);
	rte_argv[rte_argc] = rte_argvv[rte_argc];
	rte_argc++;
	snprintf(rte_argvv[rte_argc], MAX_ARGV_LEN, "--proc-type=auto");
	rte_argv[rte_argc] = rte_argvv[rte_argc];
	rte_argc++;
	rte_argv[rte_argc] = NULL;

	ret = rte_eal_init(rte_argc, (char**)rte_argv);
	if (ret < 0)
		rte_exit(EXIT_FAILURE, "Cannot init EAL\n");

	// changed in rte_eal_init
	//printf("%s\n", rte_argv[rte_argc - 1]);

	/* determine the NIC devices available */
	if (rte_eth_dev_count() == 0)
		rte_exit(EXIT_FAILURE, "No Ethernet ports - bye\n");
	
	proc_type = rte_eal_process_type();
	mp = (proc_type == RTE_PROC_SECONDARY) ?
			rte_mempool_lookup(_SMP_MBUF_POOL) :
			rte_pktmbuf_pool_create(_SMP_MBUF_POOL, NB_MBUFS,
				MBUF_CACHE_SIZE, 0, RTE_MBUF_DEFAULT_BUF_SIZE,
				rte_socket_id());
	if (mp == NULL)
		rte_exit(EXIT_FAILURE, "Cannot get memory pool for buffers\n");
	
	
	nb_ports = rte_eth_dev_count();
	printf("dev count %d\n", nb_ports);

	/* Initialize all ports. */
	if(proc_type == RTE_PROC_PRIMARY)
		for (portid = 0; portid < nb_ports; portid++)
		{
			if (smp_port_init(portid, mp, (uint16_t)num_queues) < 0)
				rte_exit(EXIT_FAILURE, "Error initialising ports\n");

			check_port_link_status((uint8_t)portid);
		}
			
	RTE_LOG(INFO, APP, "Finished Process Init.\n");

	rte_eal_mp_remote_launch(lcore_main, NULL, CALL_MASTER);

	return 0;
}
